﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MHYS.DEMO.DAL;
using MHYS.DEMO.Model;
using System.Data;
using System.Data.SqlClient;
namespace MHYS.DEMO.DAL
{
    public class UserInfoService
    {


        /// <summary>
        /// 根据用户名查询用户信息
        /// </summary>
        /// <param name="UserName">用户姓名</param>
        /// <returns>用户实体集</returns>
        public static List<UserInfo> SelectUserInfo(string UserName)
        {
            string sql = string.Format("SELECT * FROM UserInfo,RankInfo WHERE UserName='{0}' AND UserInfo.Rid=RankInfo.Rid", UserName);
            List<UserInfo> userLists = new List<UserInfo>();
            DataTable table = DBHelper.SelectDatatable(sql);
            foreach (DataRow item in table.Rows)
            {
                UserInfo user = new UserInfo() {
                    Address = item["Address"].ToString(),
                    Rid = Convert.ToInt32(item["Rid"]),
                    TrueName = item["TrueName"].ToString(),
                    Uid = Convert.ToInt32(item["Uid"].ToString()),
                    UserName = item["UserName"].ToString(),
                    UserPwd = item["UserPwd"].ToString() };
                user.RankInfo = new RankInfo() { Rid = user.Rid, RName = item["RName"].ToString() };
                userLists.Add(user);
            }
            return userLists;
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="user">实体</param>
        /// <returns>是否更新成功</returns>
        public static bool UpdateUserInfo(UserInfo user)
        {
            string sql = string.Format("UPDATE UserInfo SET UserName='{0}',UserPwd='{1}',TrueName='{2}',Address='{3}',Rid='{4}' WHERE Uid='{5}'", user.UserName, user.UserPwd, user.TrueName, user.Address, user.Rid, user.Uid);
            if (DBHelper.ExecNonQuery(sql))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 插入新用户
        /// </summary>
        /// <param name="user">用户实体</param>
        /// <returns>是否插入成功</returns>
        public static bool InsertUser(UserInfo user)
        {
            //user.Rid = Convert.ToInt32(DBHelper.SelectDatatable(string.Format("SELECT * FROM RankInfo WHERE RName='{0}'", user.RankInfo.RName)).Rows[0]["Rid"]);
            string sql = string.Format("INSERT INTO [dbo].[UserInfo]([UserName],[UserPwd],[TrueName],[Address],[Rid]) VALUES ('{0}','{1}','{2}','{3}','{4}')", user.UserName, user.UserPwd, user.TrueName, user.Address,user.Rid  );
            if (DBHelper.ExecNonQuery(sql))
            {
                return true;
            }
            else
            {
                return false;
            }
        }


    }
}
